package com.jdew.thkj.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ali.auth.third.core.MemberSDK;
import com.ali.auth.third.core.callback.LoginCallback;
import com.ali.auth.third.core.model.Session;
import com.ali.auth.third.login.LoginService;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.model.TradeResult;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.AlibcConstants;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.ScoreBean;
import com.jdew.thkj.bean.TbDetailBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.BannerViewHolder;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.CleanCacheUtil;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ZeroTbProductDetailActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.salenum)
    TextView salenum;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.banner)
    MZBannerView banner;
    @Bind(R.id.beforeprice)
    TextView yuanPrice;
    @Bind(R.id.shoucang)
    ImageView shoucang;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.name2)
    TextView name2;
    @Bind(R.id.source)
    ImageView source;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.pic_view)
    LinearLayout picView;
    private String collectionState;
    private SharedPreferences sp;
    private String shareUrl;
    private SharedPreferences.Editor editor;
    private String itemid, phone;
    private String youhuiquan;
    private List<String> list = new ArrayList<>();
    private TbDetailBean tbbena;
    private List<String> picList = new ArrayList<>();


    @Override
    public int bindLayout() {
        return R.layout.activity_zerotb_detail;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        yuanPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        title.setText("商品详情");
        CleanCacheUtil.clearAllCache(this);
        back.setVisibility(View.VISIBLE);
        itemid = getIntent().getStringExtra("itemId");
        phone = getIntent().getStringExtra("phone");
        GetProductDetail();
        getState();
        back.setOnClickListener(this);
        copy.setOnClickListener(this);
        shoucang.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.copy: {
                if (RegexValidateUtils.isAppInstalled(this, "com.taobao.taobao")) {
                    openTaoBao();
                } else {
                    ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("请先安装淘宝");
                }
            }
            break;
            case R.id.shoucang: {
                if (null != collectionState && collectionState.equals("1")) {
                    CanceltheCollection();
                } else {
                    Collection();
                }
            }
            break;
            default:
                break;
        }
    }

    public void GetProductDetail() {
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("Item_Id", itemid);
        if (null != phone && phone.equals("15325799911")) {
            map.put("UserPhone", phone);
        }
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTBItemConvert(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Item_Id" + itemid + "UserPhone" + phone)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TbDetailBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(TbDetailBean bean) {
                if (bean.getCode().equals("0")) {
                    DecimalFormat df = new DecimalFormat("0.00");
                    tbbena = bean;
                    shareUrl = bean.getData().getCoupon_click_url();
                    youhuiquan = bean.getData().getCoupon_info().replace(".00", "");
                    yuanPrice.setText("原价:" + df.format(bean.getData().getZk_final_price()));
                    salenum.setText("已售  " + bean.getData().getVolume());
                    shopname.setText(bean.getData().getNick());
                    list = bean.getData().getImageUrl();
                    banner.setPages(list, new MZHolderCreator<BannerViewHolder>() {
                        @Override
                        public BannerViewHolder createViewHolder() {
                            return new BannerViewHolder();
                        }
                    });
                    banner.setDelayedTime(5000);
                    banner.start();
                    //banner设置方法全部调用完毕时最后调用
                    if (bean.getData().getTitle().length() >= 22) {
                        name.setText(bean.getData().getTitle().substring(0, 22));
                        name2.setText(bean.getData().getTitle().substring(22, bean.getData().getTitle().length()));
                    } else {
                        name.setText(bean.getData().getTitle());
                    }
                    if (bean.getData().getUser_type().equals("0")) {
                        source.setImageResource(R.mipmap.tb);
                        shop.setImageResource(R.mipmap.tb);
                    } else {
                        source.setImageResource(R.mipmap.tm);
                        shop.setImageResource(R.mipmap.tm_shop);
                    }
                    GetShopImg();
                } else if (bean.getCode().equals("-1")) {
                    commomDialog(bean.getMessage());
                } else if (bean.getCode().equals("-7")) {
                    commomDialog(bean.getMessage());
                }
            }
        });
    }


    public void getState() {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetState(userName, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + userName + "ItemId" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    shoucang.setImageResource(R.mipmap.sc);
                    collectionState = "1";
                } else {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }

    public void CanceltheCollection() {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).CanceltheCollection(userName, itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + userName + "ItemId" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                    ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("取消收藏成功");
                } else {
                    collectionState = "1";
                    shoucang.setImageResource(R.mipmap.sc);
                    ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("取消收藏失败");
                }
            }
        });
    }

    public void Collection() {
        String userName = sp.getString("userPhone", "");
        if (null != userName && null != tbbena && null != tbbena.getData().getUser_type() && null != tbbena.getData().getTitle() && null != tbbena.getData().getVolume() && null != tbbena.getData().getPict_url() && null != tbbena.getData().getCoupon_info() && null != tbbena.getData().getWxUrl()) {
            String price = tbbena.getData().getZk_final_price() + "";
            getCollection(userName, tbbena.getData().getPict_url(), tbbena.getData().getUser_type(), tbbena.getData().getTitle(), tbbena.getData().getVolume(), price);
        }
    }

    public void getCollection(String userName, String url, String type, String title, String volume, String price) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserName", userName);
        map.put("ItemId", itemid);
        map.put("Url", url);
        map.put("Title", title);
        map.put("Price", price);
        map.put("Coupon", youhuiquan);
        map.put("Identification", type);
        map.put("volume", volume);
        map.put("ClickUrl", shareUrl);
        map.put("Commission", youhuiquan);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).YJCollection(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ItemId" + itemid + "UserName" + userName + "Url" + url + "Title" + title + "Price" + price + "Coupon" + youhuiquan + "Identification" + type + "volume" + volume + "ClickUrl" + shareUrl + "Commission" + youhuiquan)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("1")) {
                    collectionState = "1";
                    ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("收藏成功");
                    shoucang.setImageResource(R.mipmap.sc);
                } else {
                    collectionState = "-1";
                    ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("收藏失败");
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    public void openTaoBao() {                      //唤醒淘宝
        //提供给三方传递配置参数
        ToastUtils.getInstance(ZeroTbProductDetailActivity.this).showMessage("正在打开淘宝....");
        Map<String, String> exParams = new HashMap<>();
        exParams.put(AlibcConstants.ISV_CODE, "appisvcode");
        AlibcShowParams showParams = new AlibcShowParams(OpenType.Native, false);
        AlibcBasePage page = new AlibcPage(shareUrl);
        AlibcTrade.show(ZeroTbProductDetailActivity.this, page, showParams, null, exParams,
                new AlibcTradeCallback() {

                    @Override
                    public void onFailure(int i, String s) {

                    }

                    @Override
                    public void onTradeSuccess(TradeResult tradeResult) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWeiboDialog) {
            mWeiboDialog.cancel();
        }
    }
    public void GetShopImg() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetGetShopImg(itemid, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "ItemId" + itemid)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ScoreBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);

            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(ScoreBean bean) {
                if (bean.getCode().equals("0")) {
                    if (null != bean.getData()) {
                        picList = bean.getData();
                        addView();
                    }
                }
            }
        });
    }
    public void addView() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setLayoutDirection(LinearLayout.VERTICAL);
        picView.setLayoutParams(lp);
        for (int i = 0; i < picList.size(); i++) {
            ImageView imageView = new ImageView(this);
            Glide.with(this).load(picList.get(i)).into(imageView);
            picView.addView(imageView);
        }
    }

    public void commomDialog(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setPositiveButton("我知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                }).show();
    }
}
